package com.ruoyi.business.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;


import com.ruoyi.business.dao.CardetailDao;
import com.ruoyi.business.dao.InventoryDao;
import com.ruoyi.business.domain.Cardetail;
import com.ruoyi.business.dto.CardetailDto;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.business.dao.CarmainDao;
import com.ruoyi.business.domain.CarMain;
import com.ruoyi.business.service.ICarmainService;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 * carmainService业务层处理
 *
 * @author liutietou
 * @since 1.0 2025-07-15
 */
@Transactional(readOnly = true)
@Service
public class CarmainServiceImpl implements ICarmainService {

    @Autowired
    private CarmainDao carmainDao;
    @Autowired
    private CardetailDao cardetailDao;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private InventoryDao  inventoryDao;

    /**
     * 查询carmain
     *
     * @param id carmainID
     * @return carmain
     */
    @Override
    public CarMain findById(Integer id) {
        return carmainDao.findById(id).get();
    }

    /**
     * 分页查询carmain列表
     *
     * @param req carmain
     * @return carmain
     */
    @Override
    public Page<CarMain> findCarmainPage(CarMain req) {
        Specification<CarMain> example = formatQueryParams(req);
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Pageable pageable = PageRequest.of(pageDomain.getPageNo(),
                Optional.ofNullable(pageDomain.getPageSize()).orElse(PageDomain.DEFAULT_PAGE_SIZE),
                Sort.Direction.DESC,
                Optional.ofNullable(pageDomain.getOrderByColumn()).orElse("id"));
        Page<CarMain> page = carmainDao.findAll(example, pageable);
         for(CarMain carMain:  page.getContent()){
             carMain.setCardetails(this.cardetailDao.findByMainid(carMain));
         }
        return page;
    }

    /**
     * 分页查询carmain列表
     *
     * @param req carmain
     * @return carmain
     */
    @Override
    public List<CarMain> findCarmainList(CarMain req) {
        Specification<CarMain> example = formatQueryParams(req);
        List<CarMain> list = carmainDao.findAll(example, Sort.by(Sort.Direction.DESC,"createTime"));
        for(CarMain carMain:list){
            carMain.setCardetails(this.cardetailDao.findByMainid(carMain));
        }
        return list;
    }

    private Specification<CarMain> formatQueryParams(CarMain req){
        Specification<CarMain> example = new Specification<CarMain>() {
            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<CarMain> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if (null != req.getId()){
                    Predicate pre = cb.equal(root.get("id").as(Integer.class), req.getId());
                    list.add(pre);
                }
                if (null != req.getUserId()){
                    Predicate pre = cb.equal(root.get("userId").as(Long.class), req.getUserId());
                    list.add(pre);
                }
                if (list.isEmpty()) {
                    return null;
                }
                return cb.and(list.toArray(new Predicate[0]));
            }
        };
        return example;
    }

    /**
     * 保存（新增/修改）carmain
     *
     * @param carmain carmain
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(CarMain carmain) {
        carmainDao.save(carmain);
    }


    /**
     * 批量删除carmain
     *
     * @param ids 需要删除的carmainID
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByIds(List<Integer> ids) {
        List<CarMain> existBeans = carmainDao.findAllById(ids);
        if(!existBeans.isEmpty()){
            carmainDao.deleteAll(existBeans);
        }
    }

    /**
     * 删除carmain信息
     *
     * @param id carmainID
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteCarmainById(Integer id) {
         carmainDao.deleteById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
     public  void   editCar(List<CardetailDto>  list){
        SysUser sysUser=    tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        CarMain  carMain=this.carmainDao.getCarMainByUserId(sysUser);
        if(carMain==null){
            carMain=new CarMain(sysUser);
            this.carmainDao.save(carMain);
        }
        this.cardetailDao.deleteByMainid(carMain);
        List<Cardetail>  cardetailList=new ArrayList<>();
        for(CardetailDto cardetailDto:list){
            Cardetail  cardetail=new Cardetail();
            cardetail.setMainid(carMain);
            cardetail.setOrderNum(cardetailDto.getOrderNum());
           cardetail.setCinvcode(this.inventoryDao.findById(cardetailDto.getCinvcode()).get());
            cardetailList.add(cardetail);
        }
        this.cardetailDao.saveAll(cardetailList);

      }
}
